package com.wichell.framework.lock;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.log4j.Logger;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.StringUtils;

public class DistributedLockFactoryBean implements FactoryBean<DistributedLockTemplate> {
	private Logger logger = Logger.getLogger(DistributedLockFactoryBean.class);

	private LockInstanceMode mode;

	private DistributedLockTemplate distributedLockTemplate;

	private RedissonClient redisson;

	@PostConstruct
	public void init() {
		if (logger.isDebugEnabled()) {
			logger.debug("初始化分布式锁模板");
		}
		switch (mode) {
		default: {
			distributedLockTemplate = new RedissonDistributedLockTemplate(redisson);
			break;
		}
		}
	}

	@PreDestroy
	public void destroy() {
		if (logger.isDebugEnabled()) {
			logger.debug("销毁分布式锁模板");
		}
		redisson.shutdown();
	}

	@Override
	public DistributedLockTemplate getObject() throws Exception {
		return distributedLockTemplate;
	}

	@Override
	public Class<?> getObjectType() {
		return DistributedLockTemplate.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	public void setRedisson(RedissonClient redisson) {
		this.redisson = redisson;
	}

	public void setMode(String mode) {
		if (StringUtils.isEmpty(mode)) {
			throw new IllegalArgumentException("未找到分布式锁配置项");
		}
		this.mode = LockInstanceMode.parse(mode);
		if (this.mode == null) {
			throw new IllegalArgumentException("不支持的分布式锁模式");
		}
	}

	private enum LockInstanceMode {
		REDISSON;

		public static LockInstanceMode parse(String name) {
			for (LockInstanceMode modeIns : LockInstanceMode.values()) {
				if (modeIns.name().equals(name.toUpperCase())) {
					return modeIns;
				}
			}
			return null;
		}
	}
}
